package com.springboot.controller;

import com.springboot.model.*;
import com.springboot.service.FileUploadService;
import com.springboot.service.UserLoginService;
import com.springboot.util.FileUtil;
import com.springboot.util.GetServerRealPathUnit;
import com.springboot.util.SendMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 本控制台用于用户的注册
 */
@Controller
public class UserEnrollController {
    //声明业务类
    @Autowired
    UserLoginService userLoginService;
    @Autowired
    FileUploadService fileUploadService;

    //患者端注册界面响应,通过@RequestParam获取参数,获得验证码
    @CrossOrigin
    @RequestMapping(value = "/patient_enroll")//get  @getMapping    post  @postMapping
    public @ResponseBody
    String patientAuthCode(@RequestParam("phone") String tel)
    {
        System.out.println(tel + " " + "正在获取验证码");
        try{
            SendMessage send=new SendMessage(); //获得验证码
            return send.sendMessage(tel);
        }catch(Exception e)
        {
            return "False";
        }
    }
    //患者端注册界面响应,通过@RequestParam获取参数,设置用户信息
    @CrossOrigin
    @RequestMapping(value = "/patientPhoto")//get  @getMapping    post  @postMapping
    public @ResponseBody
    String patientEnroll(@RequestParam("phone") String tel,
                         @RequestParam("pass") String password,
                         @RequestParam("logoLink") MultipartFile logoLink,
                         @RequestParam("userName") String userName,
                         @RequestParam("userSex") String userSex)
    {
        System.out.println(tel + " " + "正在载入个人信息");
        try{
            if(userLoginService.findUserByTel(tel)==null)
            {
                UserLoginForm user= new UserLoginForm();
                user.setUserTel(tel);
                user.setUserPwd(password);
                user.setUserType(1);
                user.setUserName(userName);
                user.setUserSex(userSex);
                userLoginService.insertUserForm(user);
                UserLoginForm userLoginForm=userLoginService.findUserByTel(tel);
                userLoginForm.setLogoLink(fileUploadService.UploadPicture(logoLink,"userId="+userLoginForm.getUserId()));
                userLoginService.updateUserLoginForm(userLoginForm);
                NavigationRecord navigationRecord1=new NavigationRecord(userLoginForm.getUserId(), 1,1);
                userLoginService.insertNavigation(navigationRecord1);
                NavigationRecord navigationRecord2=new NavigationRecord(userLoginForm.getUserId(), 2,1);
                userLoginService.insertNavigation(navigationRecord2);
                NavigationRecord navigationRecord3=new NavigationRecord(userLoginForm.getUserId(), 3,1);
                userLoginService.insertNavigation(navigationRecord3);
                NavigationRecord navigationRecord4=new NavigationRecord(userLoginForm.getUserId(), 4,1);
                userLoginService.insertNavigation(navigationRecord4);
                return "True";
            }
            else
            {
                return "False";
            }
        }catch(Exception e)
        {
            return "False";
        }
    }

    //医生端注册界面响应,通过@RequestParam获取参数,获得验证码
    @CrossOrigin
    @RequestMapping(value = "/doctorGetCode")//get  @getMapping    post  @postMapping
    public @ResponseBody
    String doctorAuthCode(@RequestParam("tel") String tel)
    {
        System.out.println(tel + " " + "正在获取验证码");
        try{
            SendMessage send=new SendMessage(); //获得验证码
            return send.sendMessage(tel);
        }catch(Exception e)
        {
            return "False";
        }
    }
    //医生端注册界面响应,通过@RequestParam获取参数,设置用户信息
    @CrossOrigin
    @RequestMapping(value = "/docotorResgisterIn1")//get  @getMapping    post  @postMapping
    public @ResponseBody
    String doctorEnroll(@RequestParam("phone") String tel,
                        @RequestParam("pass") String password,
                        @RequestParam("name") String name,
                        @RequestParam("sex") String sex,
                        @RequestParam("doctorRank") String rank,
                        @RequestParam("hospitalName") String hospitalName,
                        @RequestParam("fieldName") String fieldName,
                        @RequestParam("avatar1") MultipartFile logoLink)
    //电话tel；密码password；头像（真实照片）logoLink；姓名name；性别sex；医生职称rank；
    //诊所名称hospitalName；科室fieldName；
    {
        System.out.println("传进来的图片路径是"+logoLink);
        try{
            if(userLoginService.findUserByTel(tel)==null)
            {
                //插入数据到用户信息表中
                UserLoginForm user= new UserLoginForm();
                user.setUserTel(tel);
                user.setUserPwd(password);
                user.setUserType(2);
                user.setUserName(name);
                user.setUserSex(sex);
                userLoginService.insertUserForm(user);
                UserLoginForm find=userLoginService.findUserByTel(tel);
                //图片上传，存在static下，相对路径为userId=?/文件名，把图片路径存在数据库中
                find.setLogoLink(fileUploadService.UploadPicture(logoLink,"userId="+find.getUserId()));
                userLoginService.updateUserLoginForm(find);
                //插入数据到医生信息表中
                DoctorInfoForm doctorInfoForm=new DoctorInfoForm();
                doctorInfoForm.setDoctorId(find.getUserId());
                doctorInfoForm.setDoctorTel(tel);
                doctorInfoForm.setDoctorName(name);
                doctorInfoForm.setDoctorRank(rank);
                userLoginService.insertById(doctorInfoForm);
                //插入数据到诊所信息表中
                ClinicForm clinicForm=new ClinicForm();
                clinicForm.setClinicName(hospitalName);
                ClinicForm findClinic=userLoginService.findClinic(hospitalName);
                if(findClinic==null) {
                    userLoginService.insertClinic(clinicForm);
                }
                //插入数据到医生科室表中
                DoctorFieldForm doctorFieldForm=new DoctorFieldForm();
                doctorFieldForm.setDoctorId(find.getUserId());
                doctorFieldForm.setDoctorField(fieldName);
                userLoginService.insertDoctorField(doctorFieldForm);
                //插入数据到认证表中
                Authentication authentication=new Authentication();
                authentication.setDoctorId(find.getUserId());
                authentication.setHeadLink(find.getLogoLink());
                ClinicForm clinicForm1=userLoginService.findByClinicName(hospitalName);
                int clinicId=clinicForm1.getClinicId();
                authentication.setClinicId(clinicId);
                userLoginService.insertAuthentication(authentication);
                System.out.println("True");
                UserLoginForm userLoginForm=userLoginService.findUserByTel(tel);
                NavigationRecord navigationRecord1=new NavigationRecord(userLoginForm.getUserId(), 5,1);
                userLoginService.insertNavigation(navigationRecord1);
                NavigationRecord navigationRecord2=new NavigationRecord(userLoginForm.getUserId(), 6,1);
                userLoginService.insertNavigation(navigationRecord2);
                NavigationRecord navigationRecord3=new NavigationRecord(userLoginForm.getUserId(), 7,1);
                userLoginService.insertNavigation(navigationRecord3);
                NavigationRecord navigationRecord4=new NavigationRecord(userLoginForm.getUserId(), 8,1);
                userLoginService.insertNavigation(navigationRecord4);
                return "True";
            }
            else
            {
                return "False";
            }
        }catch(Exception e)
        {
            return "False";
        }
    }

    //医生端注册界面响应,通过@RequestParam获取参数,设置用户信息
    @CrossOrigin
    @RequestMapping(value = "/docotorResgisterIn2")//get  @getMapping    post  @postMapping
    public @ResponseBody
    String doctorEnroll(@RequestParam("phone") String tel,
                        @RequestParam("avatar2") MultipartFile qualificationImg)
    //电话tel；行医执照qualification
    {
        System.out.println(tel + " " + "正在载入认证图片");
        try {
            //插入认证数据到认证表中
            UserLoginForm find=userLoginService.findUserByTel(tel);
            System.out.println(find.getUserId());
            Authentication authentication=userLoginService.findAuthenticationById(find.getUserId());
            //图片上传，存在static下，相对路径为userId=?/文件名，把图片路径存在数据库中
            authentication.setIdentityLink2(fileUploadService.UploadPicture(qualificationImg,"qualificationUserId="+find.getUserId()));
            userLoginService.updateAuthentication(authentication);
            System.out.println("True");
            return "True";
        } catch (Exception e) {
            return "False";
        }
    }

    //助理端注册界面响应,通过@RequestParam获取参数,获得验证码
    @CrossOrigin
    @RequestMapping(value = "/assistantGetCode")//get  @getMapping    post  @postMapping
    public @ResponseBody
    String assistantAuthCode(@RequestParam("tel") String tel)
    {
        System.out.println(tel + " " + "正在获取验证码");
        try{
            SendMessage send=new SendMessage(); //获得验证码
            return send.sendMessage(tel);
        }catch(Exception e)
        {
            return "Error";
        }
    }
    //助理端注册界面响应,通过@RequestParam获取参数,设置用户信息
    @CrossOrigin
    @RequestMapping(value = "/assistantResgisterIn1")//get  @getMapping    post  @postMapping
    public @ResponseBody
    String assistantEnroll(@RequestParam("phone") String tel,
                           @RequestParam("pass") String password,
                           @RequestParam("avatar3") MultipartFile logoLink,
                           @RequestParam("name") String name,
                           @RequestParam("sex") String sex,
                           @RequestParam("hospitalName") String hospitalName)
    {
        System.out.println(tel + " " + "正在载入个人信息");
        try{
            if(userLoginService.findUserByTel(tel)==null)
            {
                UserLoginForm assistant_user= new UserLoginForm();
                assistant_user.setUserTel(tel);
                assistant_user.setUserPwd(password);
                assistant_user.setUserType(3);
                assistant_user.setUserName(name);
                assistant_user.setUserSex(sex);
                userLoginService.insertUserForm(assistant_user);
                UserLoginForm find=userLoginService.findUserByTel(tel);
                //图片上传，存在static下，相对路径为userId=?/文件名，把图片路径存在数据库中
                find.setLogoLink(fileUploadService.UploadPicture(logoLink,"userId="+find.getUserId()));
                userLoginService.updateUserLoginForm(find);
                ClinicForm clinicForm=new ClinicForm();
                clinicForm.setClinicName(hospitalName);
                ClinicForm findClinic=userLoginService.findClinic(hospitalName);
                if(findClinic==null) {
                    userLoginService.insertClinic(clinicForm);
                }
                System.out.println("成功");
                Authentication authentication=new Authentication();
                authentication.setDoctorId(find.getUserId());
                authentication.setHeadLink(find.getLogoLink());
                ClinicForm clinicForm1=userLoginService.findByClinicName(hospitalName);
                int clinicId=clinicForm1.getClinicId();
                authentication.setClinicId(clinicId);
                UserLoginForm userLoginForm=userLoginService.findUserByTel(tel);
                userLoginService.insertAuthentication(authentication);
                NavigationRecord navigationRecord1=new NavigationRecord(userLoginForm.getUserId(), 9,1);
                userLoginService.insertNavigation(navigationRecord1);
                NavigationRecord navigationRecord2=new NavigationRecord(userLoginForm.getUserId(), 10,1);
                userLoginService.insertNavigation(navigationRecord2);
                NavigationRecord navigationRecord3=new NavigationRecord(userLoginForm.getUserId(), 11,1);
                userLoginService.insertNavigation(navigationRecord3);
                return "True";
            }
            else
            {
                return "False";
            }
        }catch(Exception e)
        {
            return "False";
        }
    }

    //助理端注册界面响应,通过@RequestParam获取参数,设置用户信息
    @CrossOrigin
    @RequestMapping(value = "/assistantResgisterIn2")//get  @getMapping    post  @postMapping
    public @ResponseBody
    String assistantEnroll(@RequestParam("phone") String tel,
                           @RequestParam("avatar4") MultipartFile qualificationImg) {
        try {
            System.out.println(tel + " " + "正在载入认证图片");
            UserLoginForm find=userLoginService.findUserByTel(tel);
            System.out.println(find.getUserId());
            Authentication authentication=userLoginService.findAuthenticationById(find.getUserId());
            //图片上传，存在static下，相对路径为userId=?/文件名，把图片路径存在数据库中
            authentication.setIdentityLink1(fileUploadService.UploadPicture(qualificationImg,"qualificationUserId="+find.getUserId()));
            userLoginService.updateAuthentication(authentication);
            return "True";
        } catch (Exception e) {
            return "False";
        }
    }

    //管理员上传头像处理
    @RequestMapping(value = "/adminUpload")
    @ResponseBody
    public String adminUpload(MultipartFile imgFile){
        System.out.println("调用upload");
        //先拿到原本图片的名称
        String originalFilename = imgFile.getOriginalFilename();
        //对文件名分割
        int i = originalFilename.lastIndexOf(".");
        String ex = originalFilename.substring(i);
        //生成一个新的文件名
        String fileName = UUID.randomUUID().toString()+ex;
        //拿到存放路径
        String path = GetServerRealPathUnit.getPath("photos");
        path = path+"admin"+"\\";
        System.out.println("图片存放路径："+path);
        try {
            FileUtil.fileupload(imgFile.getBytes(),path,fileName);
            File myfile=new File(path+fileName);
//            System.out.println(myfile.length()+"====================");
//            System.out.println(myfile.length()+"====================");
//            System.out.println(myfile.length()+"====================");
//            System.out.println(myfile.length()+"====================");
//            System.out.println(myfile.length());
//            System.out.println(myfile.length());
//            System.out.println(myfile.length());
//            System.out.println(myfile.length());
//            System.out.println(myfile.getAbsolutePath());
//            System.out.println(myfile.getName());

            fileName=myfile.getName();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("图片名称："+fileName);
      return fileName;

    }

    //管理员进行注册
    @RequestMapping("/adminRegister")
    @ResponseBody
    public String adminregister(@RequestBody UserLoginForm userLoginForm){
        if(userLoginForm.getUserTel()==null||userLoginForm.getUserTel()==""||userLoginForm.getUserPwd()==null||userLoginForm.getUserPwd()=="")return "kong";
        else if (!userLoginForm.getUserTel().matches("^1[3-9]\\d{9}$")) {
            return "illegal";
        }
        else{
            UserLoginForm user = userLoginService.findUserByTel(userLoginForm.getUserTel());
            if(user!=null&&user.getUserType()==4){
                return "has";
            }
            else {
                int i = 0;
                userLoginForm.setUserType(4);
                i = userLoginService.insertUserForm(userLoginForm);
                if(i==0)return "no";
                else return "yes";
            }
        }
    }
}
